<template>
  <div class="app-container">
    <el-form :model="queryParams2" ref="queryForm2" size="small" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="基础数据编码" prop="tableName">
        <el-input style="width: 300px" disabled="true"
          v-model="queryParams2.tableName"
          placeholder="请输入基础数据编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="基础数据编码名称" prop="tableName">
        <el-input style="width: 300px" disabled="true"
                  v-model="queryParams2.chineseName"
                  placeholder="请输入基础数据编码名称"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-if="hisVersionVal" label="版本号" prop="hisVersionVal">
        <el-input disabled="true"
                  v-model="queryParams2.hisVersionVal"
                  placeholder="请输入版本号"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </el-form>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item v-if="false" label="表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段名称" prop="prop">
        <el-input
          v-model="queryParams.prop"
          placeholder="请输入字段名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_common_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['reportworld:dispose:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['reportworld:dispose:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit-outline"
          size="mini"
          @click="handleUpdateOrderNum"
          v-hasPermi="['reportworld:dispose:orderNum']"
        >保存顺序</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['reportworld:dispose:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="initDispose"
          v-hasPermi="['reportworld:dispose:init']"
        >初始化</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['reportworld:dispose:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border="border" v-loading="loading" max-height="550px"
              :data="disposeList"
              row-key="id"
              @selection-change="handleSelectionChange"
              @sort-change="handleSortChange"
              :row-style="tableRowStyle" @row-click="rowClick"  ref="dispose">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-hasPermi="['reportworld:dispose:query']"
        label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row,false)"
            v-hasPermi="['reportworld:dispose:query']"
          >详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="表名" width="180" align="center" prop="tableName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']">
      <template slot-scope="scope">
          <span>{{scope.row.tableName ? scope.row.tableName.replace('RW_DB_',''): scope.row.tableName }}</span>
      </template>
      </el-table-column>
      <el-table-column label="字段名称" width="180" align="center" prop="prop" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="字段说明" width="180" align="center" prop="label" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="页面显示类型" width="180" align="center" prop="componentType" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="显示顺序" width="150" align="center" prop="orderNum" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="是否必填" width="150" align="center" prop="required">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.required"/>
        </template>
      </el-table-column>
      <el-table-column label="是否显示" width="150" align="center" prop="isShow">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isShow"/>
        </template>
      </el-table-column>
      <el-table-column label="是否查询条件" width="150" align="center" prop="isQuery">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isQuery"/>
        </template>
      </el-table-column>
      <el-table-column label="是否主键" width="150" align="center" prop="isPrimary">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isPrimary"/>
        </template>
      </el-table-column>
      <el-table-column label="是否业务主键" width="150" align="center" prop="isBusinessPrimary">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isBusinessPrimary"/>
        </template>
      </el-table-column>
      <el-table-column label="显示宽度" width="150" align="center" prop="width" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="字典编码" width="180" align="center" prop="codeName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']">
        <template slot-scope="scope">
          <a @click="handleDataDictDetail(scope.row)" style="color:blue;cursor:pointer;font-size: 12px;">{{scope.row.codeName}}</a>
        </template>
      </el-table-column>

      <el-table-column label="是否比较字段" width="180" align="center" prop="isCompare">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isCompare"/>
        </template>
      </el-table-column>
      <el-table-column label="正则表达式" width="180" align="center" prop="regular" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="正则提示信息" width="180" align="center" prop="regularMsg" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" width="150" align="center" prop="createBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="编辑时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="编辑人" width="150" align="center" prop="updateBy" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改基础数据配置信息对话框 -->
    <el-dialog v-if="open"  :title="title" :close-on-click-modal ="false" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段名称" prop="prop">
              <el-input v-model="form.prop" placeholder="请输入字段名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段说明" prop="label">
              <el-input v-model="form.label"  placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否必填" prop="required">
              <el-radio-group v-model="form.required">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="页面显示类型" prop="componentType">
              <el-select filterable clearable v-model="form.componentType" placeholder="请选择页面显示类型">
                <el-option
                  v-for="dict in dict.type.component_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否显示" prop="isShow">
              <el-radio-group v-model="form.isShow">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否查询条件" prop="isQuery">
              <el-radio-group v-model="form.isQuery">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否主键" prop="isPrimary">
              <el-radio-group v-model="form.isPrimary">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否业务主键" prop="isBusinessPrimary">
              <el-radio-group v-model="form.isBusinessPrimary">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="查询方式" v-if="form.isQuery == 1"  prop="selectType">
              <el-select filterable clearable v-model="form.selectType" placeholder="请选择查询方式">
                <el-option
                  v-for="dict in dict.type.select_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示宽度" prop="width">
              <el-input-number style="width: 100%" v-model="form.width" controls-position="right" :min="100"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典编码" prop="codeName">
              <el-input v-model="form.codeName" placeholder="请输入字典编码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="是否比较字段" prop="isCompare">
              <el-radio-group v-model="form.isCompare">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="正则表达式" prop="regular">
              <el-input v-model="form.regular"  placeholder="请输入正则表达式" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="正则提示信息" prop="regularMsg">
              <el-input v-model="form.regularMsg"  placeholder="请输入正则提示信息" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input-number style="width: 100%" v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_common_status"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input maxlength="500" v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isUpdate" :loading="butloading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="openDict"  :close-on-click-modal ="false"  :title="titleDict" @ :visible.sync="openDict" width="1000px" append-to-body>
      <datadict :classId="classId" :hisVersion="hisVersion"> </datadict >
      <div slot="footer" class="dialog-footer">
        <el-button @click="openDict = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listDispose, getDispose, delDispose, addDispose, updateDispose, initDispose,handleUpdateOrderNum } from "@/api/reportworld/dispose";
  import { getDatabaseByCode} from "@/api/reportworld/database";
  import Sortable from "sortablejs";
  import { getTableRowStyle } from "@/utils/yss";
  import datadict from "@/views/reportworld/datadict/index";

  export default {
    name: "Dispose",
    components: {
      datadict
    },
    dicts: ['sys_common_status', 'sys_yes_no','report_version','component_type','select_type'],
    data() {
      return {
        butloading:false,
        isUpdate:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 基础数据配置信息表格数据
        disposeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openDict:false,
        titleDict: "",
        // 传递字典编码
        classId: '',
        hisVersion:'',
        hisVersionVal:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          tableName: null,
          componentType: null,
          orderNum: null,
          required: null,
          isShow: null,
          prop: null,
          label: null,
          codeName: null,
          status: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          remark: null,
          hisVersion:null
        },
        queryParams2:{},
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          tableName: [
            { required: true, message: "表名不能为空", trigger: "blur" }
          ],
          componentType: [
            { required: true, message: "页面显示类型不能为空", trigger: "blur" }
          ],
          orderNum: [
            { required: true, message: "显示顺序不能为空", trigger: "blur" }
          ],
          prop: [
            { required: true, message: "字段名称不能为空", trigger: "blur" }
          ],
          label: [
            { required: true, message: "字段说明不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
    },
    activated() {
      const tableName = this.$route.query.code;
      const hisVersion = this.$route.query.hisVersion;
      if(tableName != undefined && tableName){
        this.queryParams.tableName = tableName;
        this.queryParams.hisVersion = hisVersion;
        this.hisVersionVal = false;
        if (this.queryParams.hisVersion) {
          this.hisVersionVal = true;
          this.queryParams2.hisVersionVal = this.queryParams.hisVersion;
        }
        this.getDatabaseByCode();
        this.getList();
      }
    },
    methods: {
      getDatabaseByCode(){
        getDatabaseByCode(this.queryParams.tableName,this.queryParams.hisVersion).then(response => {
          this.queryParams2.tableName=response.data.code.replace('RW_DB_','');
        this.queryParams2.chineseName=response.data.name;
        if(this.queryParams.hisVersion){
          this.hisVersionVal=true;
          this.queryParams2.hisVersionVal=this.queryParams.hisVersion;
        }
      });
      },
      /** 查询基础数据配置信息列表 */
      getList() {
        this.loading = true;
        listDispose(this.queryParams).then(response => {
          this.disposeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          tableName: null,
          componentType: null,
          orderNum: null,
          required: null,
          isShow: null,
          isQuery:null,
          isPrimary:null,
          isBusinessPrimary:null,
          isCompare:null,
          prop: null,
          label: null,
          codeName: null,
          status: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          remark: null,
          hisVersion:null,
          selectType:null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 返回按钮操作 */
      handleClose() {
        const obj = { path: "/reportworld/dataInfo/database" };
        this.$tab.closeOpenPage(obj);
      },
      initDispose() {
        const tableName= this.queryParams.tableName;
        const hisVersion=this.queryParams.hisVersion;
        this.$modal.confirm('初始化将覆盖原来的数据重新生成，是否确认需要初始化？').then(function() {
          return initDispose(tableName,hisVersion);
        }).then(() => {
          this.getList();
        this.$modal.msgSuccess("初始化成功");
      }).catch(() => {});
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 排序触发事件 */
      handleSortChange(column, prop, order) {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
        this.getList();
      },   // 保存排序
      handleUpdateOrderNum(){
        this.loading = true;
        let arrDispose = [];
        for (let index in this.disposeList) {
          const dispose = Object.assign({});
          dispose.id= this.disposeList[index].id;
          dispose.orderNum =parseInt(index) + 1;
          dispose.hisVersion=this.queryParams.hisVersion;
          arrDispose.push(dispose);
        }
        handleUpdateOrderNum(arrDispose).then(response => {
          this.loading = false;
        this.$modal.msgSuccess("保存顺序成功");
      });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加基础数据配置信息";
        this.isUpdate =true;
        this.form.required = parseInt(this.dict.type.sys_yes_no[1].value);
        this.form.isShow = parseInt(this.dict.type.sys_yes_no[0].value);
        this.form.componentType = this.dict.type.component_type[0].value;
        this.form.isQuery = parseInt(this.dict.type.sys_yes_no[1].value);
        this.form.isPrimary = parseInt(this.dict.type.sys_yes_no[1].value);
        this.form.isBusinessPrimary = parseInt(this.dict.type.sys_yes_no[1].value);
        this.form.isCompare = parseInt(this.dict.type.sys_yes_no[1].value);
        this.form.status = parseInt(this.dict.type.sys_common_status[0].value);
        this.form.version = this.dict.type.report_version[0].value;
        this.form.selectType = this.dict.type.select_type[0].value;
        if(this.queryParams.hisVersion){
          this.form.version =this.queryParams.hisVersion;
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row,isUpdate) {
        this.reset();
        const id = row.id || this.ids
        if(isUpdate == false){
          this.queryParams.id=id;
        }else{
          this.queryParams.id=id[0];
        }
        getDispose(this.queryParams).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改基础数据配置信息";
          this.isUpdate =true;
          if(isUpdate == false){
            this.title = "基础数据配置信息详情";
            this.isUpdate =false;
          }
      });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.butloading=true;
            this.form.hisVersion =this.queryParams.hisVersion;
            this.form.tableName=this.queryParams.tableName;
            if (this.form.id != null) {
              updateDispose(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {this.butloading=false});
            } else {
              addDispose(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {this.butloading=false});
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        const hisVersion= this.queryParams.hisVersion;
        this.$modal.confirm('是否确认删除数据项？').then(function() {
          return delDispose(ids,hisVersion);
        }).then(() => {
          this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      },
      /** 字典信息 */
      handleDataDictDetail: function(row) {
        this.openDict =true;
        this.classId = row.codeName;
        this.hisVersion=this.queryParams.hisVersion;
        this.titleDict = "字典详细信息";
      },
      /** 导出按钮操作 */
      handleExport() {
        this.queryParams.ids=JSON.stringify(this.ids);
        this.download('reportworld/dispose/export', {
          ...this.queryParams
      }, `dispose_${new Date().getTime()}.xlsx`)
      },
      tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
      },
      rowClick(row, column, event) { //单击行
        this.$refs.dispose.toggleRowSelection(row);
      }
    },
    mounted() {
      const el =  document.querySelector('.el-table__body-wrapper tbody')
      const sortable = Sortable.create(el, {
        onEnd: evt => {
        const targetRow = this.disposeList.splice(evt.oldIndex, 1)[0];
      this.disposeList.splice(evt.newIndex, 0, targetRow);
      for (let index in this.disposeList) {
        this.disposeList[index].sort = parseInt(index) + 1;
      }
    }
    });
    }
  };
</script>
